package io.gitee.cengxiaoxiao.converters;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 对LocalTime类型数据的转换器
 */
public class LocalTimeConverter implements Converter<LocalTime> {

    private static final String DefaultFormat = "HH:mm:ss";

    public static LocalTimeConverter INSTANCE() {
        return new LocalTimeConverter();
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalTime convertToJavaData(ReadCellData<?> cellData,
                                       ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) throws Exception {
        String str = cellData.getStringValue();
        if (str == null || str.isEmpty()) {
            return null;
        }
        String format = DefaultFormat;
        if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
            format = contentProperty.getDateTimeFormatProperty().getFormat();
        }
        return LocalTime.parse(str, DateTimeFormatter.ofPattern(format));
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalTime value,
                                               ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null) {
            return new WriteCellData<>();
        }
        String format = DefaultFormat;
        if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
            format = contentProperty.getDateTimeFormatProperty().getFormat();
        }
        return new WriteCellData<>(value.format(DateTimeFormatter.ofPattern(format)));
    }
}
